package com.easyfun.healthmagicbox.alarmclock;

import com.easyfun.healthmagicbox.ProfileActivity;
import com.easyfun.healthmagicbox.SubLastProfileActivity;
import com.easyfun.healthmagicbox.pojo.AlarmClock;
import com.easyfun.healthmagicbox.pojo.ConstantData;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {

	private static final String TAG = AlarmReceiver.class.getSimpleName();

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.content.BroadcastReceiver#onReceive(android.content.Context,
	 * android.content.Intent)
	 */
	@Override
	public void onReceive(Context context, Intent intent) {
		long currentTime = System.currentTimeMillis();
		Log.d(TAG, "the time is up,start the alarm...");
		Toast.makeText(context, "闹钟时间到了！", Toast.LENGTH_SHORT).show();
		
		String personID = intent.getStringExtra(ConstantData.HMBPERSONID);
		String cycle = intent.getStringExtra("cycle");
		String startTime = intent.getStringExtra("startTime");
		String alarmNum = intent.getStringExtra("alarmNum");
		String alarmDesc = intent.getStringExtra("alarmDesc");
		
		//-----------------------------------------------------------
		// Start UI
		//-----------------------------------------------------------
		final Intent intent_pp = new Intent(
				context, AlarmActivity.class);
		Bundle bundle = new Bundle();
		bundle.putString(ConstantData.HMBPERSONID, personID);
		bundle.putString("alarmDesc", alarmDesc);
		intent_pp.putExtras(bundle);
		intent_pp.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent_pp);
		
		// set next alarm
		AlarmClock ac = new AlarmClock();
		ac.setClockid(alarmNum);
		ac.setPersonID(personID);
		ac.setDescription(alarmDesc);
		ac.setStartTimeInMills(startTime);
		ac.setCycle(cycle);
		
		long repeat = AlarmRepeatCalculater.getNextAlarmTime(ac);
		if (repeat != 0)
		{
			PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
					Integer.valueOf(alarmNum), intent, PendingIntent.FLAG_CANCEL_CURRENT);
			
			// 获取闹钟管理器
			AlarmManager alarmManager = (AlarmManager) context
					.getSystemService(Context.ALARM_SERVICE);
			
			// 设置闹钟
			alarmManager.set(AlarmManager.RTC_WAKEUP, repeat, pendingIntent);

			Log.d(TAG, "set the time to " + String.valueOf(currentTime) + ",desc:" + alarmDesc);
		}else
		{
			Log.i(TAG,"no next alarm clock");
		}
		
	}
}
